<template>
    <div class="menuTree">
        <div class="menuTree_scroll">
            <div class="menuTree_content">
                <el-tree ref="treeRef" :default-expanded-keys="expandedList.list" :data="treeList.tree" node-key="id"
                    :props="defaultProps" @node-click="handleNodeClick" :current-node-key="currentKey" accordion
                    highlight-current @node-expand="node_expand" @node-collapse="node_collapse" />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ElTree } from 'element-plus'
import { schedulingGroup_treeData } from '@/http/scheduling';
import { useMain, store } from "@/store/index";
import { storeToRefs } from 'pinia';

const router = useRouter();
const companyId: string = router.currentRoute.value.query.id ? router.currentRoute.value.query.id.toString() : '';//公司id

interface Tree {
    childList?: Tree[];
    // childList?: Array<any>;
    id: string;
    idPath: string;
    level: number;
    name: string;
    parentId: string;
}

const useMainStore = useMain(store);//pinia

//currentProjectInfo 当前项目信息
//storeToRefs 保持响应式
let { currentProjectInfo } = storeToRefs(useMainStore);

//展开项
const expandedList = reactive({
    list: ['0']
})

const treeList = reactive({
    tree: [] as Array<Tree>,//树形结构数据,加上部门列表
    list: [] as any,//树形结构数据
})



//emit(父组件中的自定义方法)
const emit = defineEmits(['getCheckItem']);

//节点被点击触发事件
const handleNodeClick = (checked_data: Tree) => {
    // console.log('checked_data', checked_data);
    currentKey.value = checked_data.id;
    // console.log('选中的项', ckecked_item);
    emit('getCheckItem', checked_data)
}

//指定组件children和label对应的属性值
const defaultProps = {
    children: 'childList',
    label: 'name',
}

const treeRef = ref<InstanceType<typeof ElTree>>()
let currentKey = ref('0');


//获取列表数据
const getTreeList = (isfirst?: string) => {
    //如果切换到使用类型,已有数据,则不用再请求
    if (isfirst && isfirst == 'isfirst' && treeList.tree.length > 0) {
        return
    }
    schedulingGroup_treeData().then((res: any) => {
        if (res && res.result) {
            treeList.list = res.result;
            treeList.tree = [{
                id: '0',
                name: "班组列表",
                childList: res.result,
                level: 0,
                idPath: "0",
            }] as any;

            //如果是第一次调用,默认展开全部类型,默认点击全部类型
            if (isfirst && isfirst == 'isfirst') {
                // expandedList.list = [treeList.tree[0].id]
                emit('getCheckItem', treeList.tree[0]);
                currentKey.value = '0';

            }
            // console.log('expandedList.list',expandedList.list);

            nextTick(() => {
                treeRef.value?.setCurrentKey(currentKey.value);
            })
        }
    })
}

//节点被展开时触发的事件
const node_expand = (data: any) => {
    currentKey.value = data.id;
    // console.log('选中的项', ckecked_item);
    emit('getCheckItem', data)
    // console.log('data01', data);
    delEquativeNode(data, treeList.tree);//删除同级节点及子级节点
    // 在节点展开是添加到默认展开数组
    expandedList.list.push(data.id);
}


//删除同级节点及子级节点
const delEquativeNode = (data: any, treeItem: any) => {
    //遍历找出同级节点,展开数组中level相同的节点(最多有一个)
    treeItem = treeItem ? treeItem : [];
    expandedList.list.forEach(item => {
        let equativeNode = treeItem.find((item2: any) => {
            return item2.id == item && item2.level == data.level
        })
        //如果找到了同级节点,删除当前节点,并且调用删除子节点方法
        if (equativeNode) {
            expandedList.list.splice(expandedList.list.indexOf(equativeNode.id), 1);//删除当前节点
            removeChildrenIds(equativeNode);//调用删除子节点方法
        } else {//如果没找到同级节点,递归调用
            treeItem.forEach((item2: any) => {
                delEquativeNode(data, item2.childList)
            })
        }
    })
}

//节点被关闭时触发的事件
const node_collapse = (data: any) => {
    currentKey.value = data.id;
    emit('getCheckItem', data)
    // 收起时删除数组里对应选项
    expandedList.list.splice(expandedList.list.indexOf(data.id), 1);
    // 这里主要针对多级树状结构，当关闭父节点时，递归删除父节点下的所有子节点
    removeChildrenIds(data);
}

// 删除树子节点
const removeChildrenIds = (data: any) => {
    if (data.childList && data.childList.length > 0) {
        data.childList.forEach((item: any) => {
            const index = expandedList.list.indexOf(item.id)
            if (index != -1) {
                expandedList.list.splice(index, 1)
            }
            removeChildrenIds(item)
        })
    }
}

getTreeList('isfirst');

//暴露方法,父组件才能调用
defineExpose({ getTreeList })
</script>

<style scoped lang="scss">
.menuTree {
    flex-shrink: 0;
    width: 240px;
    flex-basis: 240px;
    height: 100%;
    margin-right: 0;
    // padding: 40px 10px 10px 10px;
    // padding-top: 40px;
    overflow: hidden;

    .menuTree_scroll {
        padding: 10px;
        height: 100%;
        background: rgb(255, 255, 255);
        border-radius: 8px;
    }

    .menuTree_content {
        width: 100%;
        height: 100%;
        padding-left: 4px;
        overflow: auto;

        .el-tree {
            height: auto;
            // width: auto;
            display: inline-block;
            min-width: 100%;

            :deep(.el-tree-node) {
                .el-tree-node__content {
                    height: 55px;
                    line-height: 55px;

                    .el-tree-node__label {
                        font-size: 14px;
                        color: rgba(0, 0, 0, 1);
                        font-weight: 700;
                    }

                    .el-tree-node__expand-icon {
                        font-size: 16px;
                    }
                }

                .el-tree-node__children {
                    height: auto;
                    overflow: unset;

                    .el-tree-node__content {
                        height: 55px;

                        .el-tree-node__label {
                            font-size: 14px;
                            font-weight: 400;
                            letter-spacing: 0px;
                            line-height: 55px;
                            color: rgba(0, 0, 0, 1);
                        }
                    }

                }
            }



        }
    }



}
</style>
